package org.jwcloud.project.module.zx.project.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.crypto.Data;

import org.jwcloud.project.module.zx.base.BaseServiceImpl;
import org.jwcloud.project.module.zx.dao.RtaItemSzColDAO;
import org.jwcloud.project.module.zx.dao.RtaItemSzInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaProTaskInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaProjectInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaTaskInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaTaskItemRelDAO;
import org.jwcloud.project.module.zx.dao.RtaTaskSzInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaTemplateInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaWorkInfoDAO;
import org.jwcloud.project.module.zx.db.domain.RtaProTaskInfo;
import org.jwcloud.project.module.zx.db.domain.RtaProjectInfo;
import org.jwcloud.project.module.zx.db.domain.RtaTaskInfo;
import org.jwcloud.project.module.zx.db.domain.RtaTaskSzInfo;
import org.jwcloud.project.module.zx.db.domain.RtaTemplateInfo;
import org.jwcloud.project.module.zx.db.domain.RtaWorkInfo;
import org.jwcloud.project.module.zx.info.service.TodoListTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jw.mid.mm.comm.common.pagination.ListBounds;
import com.jw.mid.mm.comm.common.pagination.ListSlice;
import com.jw.mid.mm.comm.common.repository.CrudRepository;
import com.jw.mid.mm.comm.error.exception.BusiRuntimeException;

@Service
@Transactional
public class ProjectServiceImpl extends BaseServiceImpl implements ProjectService {

	@Autowired
	private RtaProjectInfoDAO rtaProjectInfoDAO;
	@Autowired
	private RtaProTaskInfoDAO rtaProTaskInfoDAO;
	@Autowired
	private RtaWorkInfoDAO rtaWorkInfoDAO;
	@Autowired
	private RtaTaskInfoDAO rtaTaskInfoDAO;
	@Autowired
	private RtaTaskSzInfoDAO rtaTaskSzInfoDAO;
	@Autowired
	private RtaTaskItemRelDAO rtaTaskItemRelDAO;
	@Autowired
	private RtaItemSzColDAO rtaItemSzColDAO;
	@Autowired
	private RtaItemSzInfoDAO rtaItemSzInfoDAO;
	@Autowired
	private RtaTemplateInfoDAO rtaTemplateInfoDAO;

	@Override
	public void doProjectInsert(RtaProjectInfo projectInfo) {
		Integer maxPrjId = rtaProjectInfoDAO.findMaxId();
		if (maxPrjId == null) {
			maxPrjId = Integer.valueOf(1);
		} else {
			maxPrjId = maxPrjId + 1;
		}

		projectInfo.setId(maxPrjId.intValue());
		// 保存项目基本信息--有效
		projectInfo.setIsValid(01);
		projectInfo.setAppPhase("01");
		// 项目状态，进行中
		projectInfo.setStates("10");
		rtaProjectInfoDAO.create(projectInfo);
		// 开启线程
//		Thread t = new Thread(new Runnable() {
//			public void run() {
		// 模板ID
		Integer templateId = projectInfo.getRelTemplateId();
		// 查询初始工作
		List<RtaWorkInfo> listRtaWorkInfoFirst = rtaWorkInfoDAO.findFirstByTemplateId(templateId);
		Date startTime = projectInfo.getStartTime();
		if (startTime == null) {
			throw new BusiRuntimeException("请输入正确的项目启动时间！");
		}
		Integer durTime = 0;
		projectPlan(projectInfo, templateId, listRtaWorkInfoFirst, startTime);

		//
		checkIsCurrentTask(projectInfo.getId());

//			}
//		});
//		t.start();

	}

	private void checkIsCurrentTask(Integer prjId) {

		RtaProjectInfo rtaProjectInfo = rtaProjectInfoDAO.findById(prjId);
		// 查询初始工作
		List<RtaWorkInfo> listRtaWorkInfoFirst = rtaWorkInfoDAO
				.findFirstByTemplateId(rtaProjectInfo.getRelTemplateId());
		for (RtaWorkInfo rtaWorkInfo : listRtaWorkInfoFirst) {
			// 1当前进行任务 0非当前进行任务
			Integer isCurrent = RtaProTaskInfo.IS_CURRENT_YES;
			// 查询工作对应的任务,计算任务时间计划
			List<RtaTaskInfo> listRtaTaskInfo = rtaTaskInfoDAO.findByWorkId(rtaWorkInfo.getId());
			for (RtaTaskInfo rtaTaskInfo : listRtaTaskInfo) {

				Integer taskId = rtaTaskInfo.getId();
				RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(prjId, rtaWorkInfo.getId(), taskId);
				if (rtaProTaskInfo.getIsCurrent() != null
						&& rtaProTaskInfo.getIsCurrent().intValue() == RtaProTaskInfo.IS_CURRENT_NO
						&& isCurrent == RtaProTaskInfo.IS_CURRENT_YES) {
					rtaProTaskInfo.setIsCurrent(RtaProTaskInfo.IS_CURRENT_YES);
					isCurrent = RtaProTaskInfo.IS_CURRENT_NO;
				}
				rtaProTaskInfoDAO.update(rtaProTaskInfo);
			}
		}
	}

	@Override
	public void doProjectUpdate(RtaProjectInfo param) {
		rtaProjectInfoDAO.update(param);

	}

	@Override
	public void doProjectDel(Integer id) {
		RtaProjectInfo rtaProjectInfo = rtaProjectInfoDAO.findById(id);
		rtaProjectInfo.setIsValid(0);
		rtaProjectInfoDAO.update(rtaProjectInfo);

	}

	@Override
	public ListSlice<RtaProjectInfo> doProjectList(ListBounds listBounds, Map param) {
		List<RtaProjectInfo> list = rtaProjectInfoDAO.searchPrjByPage(listBounds, param);
		Long total = rtaProjectInfoDAO.searchPrjByPageCount(param);
		for (RtaProjectInfo rtaProjectInfo : list) {
			rtaProjectInfo.setCreatePerson(getUserName(rtaProjectInfo.getCreatePerson()));
			rtaProjectInfo.setCreateDept(getDeptName(rtaProjectInfo.getCreateDept()));
			rtaProjectInfo.setCreateOrg(getDeptName(rtaProjectInfo.getCreateOrg()));
			//
			rtaProjectInfo.setUpdatePerson(getUserName(rtaProjectInfo.getUpdatePerson()));
			rtaProjectInfo.setUpdateDept(getDeptName(rtaProjectInfo.getUpdateDept()));
			rtaProjectInfo.setUpdateOrg(getDeptName(rtaProjectInfo.getUpdateOrg()));
			//
			Integer relTemplateId = rtaProjectInfo.getRelTemplateId();
			RtaTemplateInfo rtaTemplateInfo = rtaTemplateInfoDAO.findById(relTemplateId);
			if (rtaTemplateInfo != null) {
				rtaProjectInfo.setRelTemplateName(rtaTemplateInfo.getTemplateName());
			}
		}
		ListSlice<RtaProjectInfo> slice = new ListSlice<>(total, list);

		return slice;
	}

	@Override
	public CrudRepository getRepository() {
		// TODO Auto-generated method stub
		return null;
	}

	private void projectPlan(RtaProjectInfo projectInfo, Integer templateId, List<RtaWorkInfo> listRtaWorkInfoFirst,
			Date startTime) {

		Integer maxDurTime = 0;
		Date nexStartTime = startTime;
		for (RtaWorkInfo rtaWorkInfoFirist : listRtaWorkInfoFirst) {
			Integer workid = rtaWorkInfoFirist.getId();
			Map map = workPlan(projectInfo, workid, startTime);
			Integer newDurTime = (Integer) map.get("durTime");
			if (maxDurTime < newDurTime) {
				maxDurTime = newDurTime;
				nexStartTime = (Date) map.get("startTime");
			}
		}
		// 查询后置工作
		for (RtaWorkInfo rtaWorkInfoFirist : listRtaWorkInfoFirst) {
			Integer parentWorkId = rtaWorkInfoFirist.getId();
			List<RtaWorkInfo> listRtaWorkInfo = rtaWorkInfoDAO.findByParentWorkId(templateId, parentWorkId);
			if (listRtaWorkInfo != null && listRtaWorkInfo.size() > 0) {
				projectPlan(projectInfo, templateId, listRtaWorkInfo, nexStartTime);
			}
		}
	}

	private Map workPlan(RtaProjectInfo projectInfo, Integer workid, Date startTime) {
		// 查询工作
		RtaWorkInfo rtaWorkInfo = rtaWorkInfoDAO.findById(workid);
		//
		Integer totalDurTime = 0;
		// 查询前置工作
		List<RtaWorkInfo> parentWorkInfos = rtaWorkInfoDAO.findParentWorkId(projectInfo.getRelTemplateId(), workid);
		// 判断前置工作是否有无限期任务
		boolean haveNullDurTime = false;
		for (RtaWorkInfo parentWorkInfo : parentWorkInfos) {
			List<RtaTaskInfo> listRtaTaskInfo = rtaTaskInfoDAO.findByWorkId(parentWorkInfo.getId());
			for (RtaTaskInfo rtaTaskInfo : listRtaTaskInfo) {
				Integer durTime = rtaTaskInfo.getDurTime();
				if (durTime == null || durTime < 1) {
					haveNullDurTime = true;
				}
			}
		}

		// 查询工作对应的任务,计算任务时间计划
		List<RtaTaskInfo> listRtaTaskInfo = rtaTaskInfoDAO.findByWorkId(rtaWorkInfo.getId());

		for (RtaTaskInfo rtaTaskInfo : listRtaTaskInfo) {
			RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(projectInfo.getId(), rtaWorkInfo.getId(),
					rtaTaskInfo.getId());
			if (rtaProTaskInfo == null) {
				// RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.f
				rtaProTaskInfo = new RtaProTaskInfo();
				// 关联项目表 外键 rta_project_info.id
				rtaProTaskInfo.setRelProId(projectInfo.getId());
				// 关联模板表 外键 rta_template_info.id
				rtaProTaskInfo.setRelTemplateId(projectInfo.getRelTemplateId());
				// 关联工作模板表 rta_work_info.id 外键
				rtaProTaskInfo.setRelWorkId(rtaWorkInfo.getId());
				// 1完成 0未完成
				rtaProTaskInfo.setIsDone(RtaProTaskInfo.IS_DONE_NO);
				// 1当前进行任务 0非当前进行任务
				rtaProTaskInfo.setIsCurrent(RtaProTaskInfo.IS_CURRENT_NO);

				//
				rtaProTaskInfo.setCronLockFlagTip(0);
				rtaProTaskInfo.setCronLockFlagWarn1(0);
				rtaProTaskInfo.setCronLockFlagWarn2(0);
				// 责任部门
				rtaProTaskInfo.setDutyDept(rtaTaskInfo.getDutyDept());
				// 关联任务模板表 rta_task_info.id 外键
				rtaProTaskInfo.setRelTaskId(rtaTaskInfo.getId());
				// 完成时间
				rtaProTaskInfo.setDoneTime(null);
				rtaProTaskInfo.setIsValid(1);
				rtaProTaskInfo.setSpFlag(RtaProTaskInfo.SP_FLAG_INIT);
				//
				Integer durTime = rtaTaskInfo.getDurTime();
				rtaProTaskInfo.setDurTime(durTime);

				if (haveNullDurTime == false) {
					// 下一任务开始时间
					// 任务开始时间
					rtaProTaskInfo.setStartTime(startTime);
					if (durTime != null && durTime > 0 && startTime != null) {
						startTime = nextWorkDate(startTime, durTime);
						totalDurTime = totalDurTime + durTime;
					} else {
						totalDurTime = 0;
						startTime = null;
					}
				}
				rtaProTaskInfoDAO.create(rtaProTaskInfo);
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("startTime", startTime);
		map.put("durTime", totalDurTime);
		return map;
	}

	@Override
	public void doProjectCommit(Integer id) {
		RtaProjectInfo rtaProjectInfo = rtaProjectInfoDAO.findById(id);

		// 项目状态--归档
		rtaProjectInfo.setStates("99");
		rtaProjectInfo.setGuidangTime(getDBDate());
		rtaProjectInfoDAO.update(rtaProjectInfo);
	}
}
